package com.kye.express.business.verification;

import android.arch.lifecycle.Lifecycle;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.App;
import com.kye.express.R;
import com.kye.express.databinding.LayoutVerification2Binding;
import com.kye.express.databinding.LayoutVerificationBinding;
import com.kye.express.view.ToastManager;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.base.RetrofitManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.jd.shop.JDCheckConsumeAvailableResultBean;
import com.kye.model.bean.jd.shop.JDCheckUploadAddressAvailableResultBean;
import com.kye.model.bean.jd.shop.request.RequestJDCheckConsumeAvailable;
import com.kye.model.bean.jd.shop.request.RequestJDCheckUploadAddressAvailable;
import com.kye.model.bean.verification.PictureVerificationResultBean;
import com.kye.model.bean.verification.request.RequestAutoSendMessage;
import com.kye.model.bean.verification.request.RequestPictureVerification;
import com.kye.model.bean.verification.request.RequestSmsVerification;
import com.kye.model.gson_adapter.ApiException;
import com.kye.model.service.JDService;
import com.kye.model.service.VerificationService;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.tuo.customview.VerificationCodeView;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 06/02/2018
 * @updated : 06/02/2018
 * @description : <Description>
 * @update_reason : <UpdateReason>
 *
 *     兑换验证业务
 */

public class ExchangeVerificationService {

    private JDService jdService;
    private VerificationService verificationService;
    private String phone;
    private int valiteType; // 验证类型,1.京东兑换2.红包兑换3.唯品卡兑换
    private LifecycleProvider<Lifecycle.Event> provider;
    private String validationCode;
    private boolean validationCodeSuccess;
    private String smsCode;
    private String smsChannel;
    private int type; //短信类型（type=2为兑换礼品获取验证码 type=3为红包获取验证码 type=4为提现获取验证码）
    private Disposable timerDisposable;
    private Disposable timerDisposable2;

    public ExchangeVerificationService(String phone, int valiteType) {
        this.phone = phone;
        this.valiteType = valiteType; // 验证类型,1.京东兑换2.红包兑换3.唯品卡兑换
        jdService = RetrofitManager.getInstance().createOpenApiService(JDService.class);
        verificationService = RetrofitManager.getInstance().createOpenApiService(VerificationService.class);
    }

    public void setProvider(LifecycleProvider<Lifecycle.Event> provider) {
        this.provider = provider;
    }

    /**
     *
     * @param onVerificationCheckListener
     */
    public void check(final OnVerificationCheckListener onVerificationCheckListener) {

        Single.just(new RequestJDCheckUploadAddressAvailable())
                .doOnSuccess(new Consumer<RequestJDCheckUploadAddressAvailable>() {
                    @Override
                    public void accept(RequestJDCheckUploadAddressAvailable requestJDCheckUploadAddressAvailable) throws Exception {
                        requestJDCheckUploadAddressAvailable.setValiteType(String.valueOf(valiteType));
                        requestJDCheckUploadAddressAvailable.setPhone(phone);
                    }
                })
                /***
                 * 判断是否满足通讯录
                 */
                .flatMap(new Function<RequestJDCheckUploadAddressAvailable, SingleSource<OpenApiResult<JDCheckUploadAddressAvailableResultBean>>>() {
                    @Override
                    public SingleSource<OpenApiResult<JDCheckUploadAddressAvailableResultBean>> apply(RequestJDCheckUploadAddressAvailable requestJDCheckUploadAddressAvailable) throws Exception {
                        return jdService.checkUploadAddressAvailable(requestJDCheckUploadAddressAvailable)
                                .compose(provider.bindUntilEvent(Lifecycle.Event.ON_DESTROY));
                    }
                })
                .doOnSuccess(new Consumer<OpenApiResult<JDCheckUploadAddressAvailableResultBean>>() {
                    @Override
                    public void accept(OpenApiResult<JDCheckUploadAddressAvailableResultBean> result) throws Exception {
                        if (result != null && result.isSuccess()) {
                            String type = result.getData().getType();
                            // 类型0-不可兑换，1-可以兑换
                            switch (type) {
                                case "0":
                                    throw new VerificationExceptionCannotExchange(result.getData().getCommTypeMsg());
                                case "1":
                                    break;
                                default:
                                    break;
                            }
                        } else {
                            throw new ApiException(result);
                        }
                    }
                })
                /**
                 * 判断能够消费
                 */
                .flatMap(new Function<OpenApiResult<JDCheckUploadAddressAvailableResultBean>, SingleSource<OpenApiResult<JDCheckConsumeAvailableResultBean>>>() {
                    @Override
                    public SingleSource<OpenApiResult<JDCheckConsumeAvailableResultBean>> apply(OpenApiResult<JDCheckUploadAddressAvailableResultBean> result) throws Exception {
                        return Single.just(new RequestJDCheckConsumeAvailable())
                                .doOnSuccess(new Consumer<RequestJDCheckConsumeAvailable>() {
                                    @Override
                                    public void accept(RequestJDCheckConsumeAvailable requestJDCheckConsumeAvailable) throws Exception {
                                        requestJDCheckConsumeAvailable.setPhone(phone);
                                    }
                                })
                                .flatMap(new Function<RequestJDCheckConsumeAvailable, SingleSource<OpenApiResult<JDCheckConsumeAvailableResultBean>>>() {
                                    @Override
                                    public SingleSource<OpenApiResult<JDCheckConsumeAvailableResultBean>> apply(RequestJDCheckConsumeAvailable requestJDCheckConsumeAvailable) throws Exception {
                                        return jdService.checkConsumeAvailable(requestJDCheckConsumeAvailable)
                                                .compose(provider.bindUntilEvent(Lifecycle.Event.ON_DESTROY));
                                    }
                                })
                                .compose(provider.bindUntilEvent(Lifecycle.Event.ON_DESTROY));
                    }
                })
                /**
                     0	操作成功
                     30000	操作失败
                     30003	查无数据
                     30037	手机未注册
                     33054	为了保证礼品能寄送到您的手上，需要发送短信进行验证
                     30031	系统维护中
                 */
                .doOnSuccess(new Consumer<OpenApiResult<JDCheckConsumeAvailableResultBean>>() {
                    @Override
                    public void accept(OpenApiResult<JDCheckConsumeAvailableResultBean> result) throws Exception {
                        if (result != null && result.isSuccess()) {

                        } else if (!result.isSuccess()) {
                            if (result.getCode() == 33054) {
                                // 是否黑名单,0-需要短信验证,1-符合要求,2-账号异常
                                throw new VerificationExceptionNeedSendSMS(result.getMsg(), result.getData().getSmsChannel(), result.getData().getPhone(), result.getData().getType());
                            } else {
                                throw new ApiException(result);
                            }
                        } else {
                            throw new ApiException(result);
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<OpenApiResult<JDCheckConsumeAvailableResultBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        onVerificationCheckListener.onLoading();
                    }

                    @Override
                    public void onSuccess(OpenApiResult<JDCheckConsumeAvailableResultBean> result) {
                        onVerificationCheckListener.onLoaded();
                        JDCheckConsumeAvailableResultBean data = result.getData();
                        String type = data.getType();
//                        是否黑名单,0-需要短信验证,1-符合要求,2-账号异常
                        switch (type) {
                            case "0":
                                onVerificationCheckListener.onVerifyByAutoSendMessage(data.getSmsChannel(), data.getType(), phone);
                                break;
                            case "1":
                                onVerificationCheckListener.onVerifyByPictureSms(data.getSmsChannel(), data.getType(), phone);
                                break;
                            case "2":
                                onVerificationCheckListener.onAccountError(result.getMsg(), result.getData().getSmsChannel(), result.getData().getType(), result.getData().getPhone());
                                break;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        onVerificationCheckListener.onLoaded();
                        if (e instanceof ApiException) {
                            ApiException apiException = (ApiException) e;
                            onVerificationCheckListener.onOpenApiError(apiException.getOpenApiResult());
                        } else if (e instanceof VerificationExceptionCannotExchange) {
                            onVerificationCheckListener.onCannotExchangeError(e.getMessage());
                        } else if (e instanceof VerificationExceptionNeedSendSMS) {
                            VerificationExceptionNeedSendSMS verificationExceptionNeedSendSMS = (VerificationExceptionNeedSendSMS) e;
                            /**
                             * 需要短信验证
                             */
                            switch (verificationExceptionNeedSendSMS.type) {
                                case "0":
                                    onVerificationCheckListener.onVerifyByAutoSendMessage(verificationExceptionNeedSendSMS.smsChannel, verificationExceptionNeedSendSMS.type, verificationExceptionNeedSendSMS.phone);
                                    break;
                                case "1":
                                    onVerificationCheckListener.onVerifyByPictureSms(verificationExceptionNeedSendSMS.smsChannel, verificationExceptionNeedSendSMS.type, verificationExceptionNeedSendSMS.phone);
                                    break;
                                case "2":
                                    onVerificationCheckListener.onAccountError(verificationExceptionNeedSendSMS.message, verificationExceptionNeedSendSMS.smsChannel, verificationExceptionNeedSendSMS.type, verificationExceptionNeedSendSMS.phone);
                                    break;
                            }
//                            onVerificationCheckListener.onNeedSendSmsError(verificationExceptionNeedSendSMS.getMessage(), verificationExceptionNeedSendSMS.smsChannel, String.valueOf(valiteType), verificationExceptionNeedSendSMS.phone);
                        } else {
                            onVerificationCheckListener.onOtherError(e);
                        }
                    }
                });
    }

    private class VerificationExceptionCannotExchange extends RuntimeException {
        public VerificationExceptionCannotExchange(String message) {
            super(message);
        }
    }

    private class VerificationExceptionNeedSendSMS extends RuntimeException {
        public String message;
        public String smsChannel;
        public String phone;
        public String type;
        public VerificationExceptionNeedSendSMS(String message, String smsChannel, String phone, String type) {
            super(message);
            this.message = message;
            this.smsChannel = smsChannel;
            this.phone = phone;
            this.type = type;
        }
    }

    public static interface OnVerificationCheckListener {

        void onLoading();

        void onLoaded();

        // 不满足通讯录条件接口
        void onCannotExchangeError(String msg);

        // 为了保证礼品能寄送到您的手上，需要发送短信进行验证
        @Deprecated
        void onNeedSendSmsError(String msg, String smsChannel, String type, String phone);

        void onAccountError(String msg, String smsChannel, String type, String phone);

        void onOpenApiError(OpenApiResult openApiResult);

        void onOtherError(Throwable e);

        // 0-需要短信验证
        void onVerifyByAutoSendMessage(String smsChannel, String type, String phone);

        // 1-符合要求
        void onVerifyByPictureSms(String smsChannel, String type, String phone);
    }

    /**
     * 类型（
     * type=0为新用户注册时获取验证码
     * type=1为找回密码获取验证码
     * type=2为兑换礼品获取验证码
     * type=3为红包获取验证码
     * type=4为提现获取验证码
     * type=5为登录获取验证码(不需要图型动态码)
     * type=6为登录获取验证码
     * type=7为查询运费获取验证码）
     * @param context
     * @param type
     * @param onVerificationOptionByPictureSmsListener
     */
    public void showVerificationByPictureSmsDialog(Context context, int type, final OnVerificationOptionByPictureSmsListener onVerificationOptionByPictureSmsListener) {
        MaterialDialog mDialog = new MaterialDialog.Builder(context)
                .customView(R.layout.layout_verification, true)
//                .positiveText("确定")
//                .negativeText("取消")
//                .onPositive(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        /**
//                         * 确认兑换
//                         */
//                        Logger.d("确认兑换");
//                        EditText smsCode = dialog.getCustomView().findViewById(R.id.sms_code);
//                        String smsCodeInput = smsCode.getText().toString();
//                        if (TextUtils.isEmpty(smsCodeInput)) {
//                            ToastManager.show(context, "请输入验证码");
//                            return;
//                        }
//                        onVerificationOptionByPictureSmsListener.toExchange(smsCodeInput);
//                    }
//                })
//                .onNegative(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        /**
//                         * 取消兑换
//                         */
//                        Logger.d("取消兑换");
//                        if (timerDisposable != null && !timerDisposable.isDisposed()) {
//                            timerDisposable.dispose();
//                        }
//                    }
//                })
                .build();
        View customView = mDialog.getCustomView();
        LayoutVerificationBinding binding = DataBindingUtil.bind(customView);
        RxView.clicks(binding.getNewPicture)
                .compose(provider.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        getPictureCode(context, phone, binding, onVerificationOptionByPictureSmsListener);
                    }
                });
        RxView.clicks(binding.getSmsCode)
                .compose(provider.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        String validationCode = binding.validationCode.getText().toString();
                        if (TextUtils.isEmpty(validationCode)) {
                            ToastManager.show(context, "请输入动态码");
                            return;
                        }
                        getSmsCode(phone, validationCode, String.valueOf(type), binding, onVerificationOptionByPictureSmsListener);
                    }
                });
        RxView.clicks(binding.cancel)
                .compose(provider.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * 取消兑换
                         */
                        Logger.d("取消兑换");
                        if (timerDisposable != null && !timerDisposable.isDisposed()) {
                            timerDisposable.dispose();
                        }
                        validationCodeSuccess = false;
                        mDialog.dismiss();
                    }
                });
        RxView.clicks(binding.confirm)
                .compose(provider.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Logger.d("确认兑换");
                        if (!validationCodeSuccess) {
                            ToastManager.show(context, "动态码不正确");
                            return;
                        }
                        EditText smsCode = mDialog.getCustomView().findViewById(R.id.sms_code);
                        String smsCodeInput = smsCode.getText().toString();
                        if (TextUtils.isEmpty(smsCodeInput)) {
                            ToastManager.show(context, "请输入验证码");
                            return;
                        }
                        onVerificationOptionByPictureSmsListener.toExchange1(smsCodeInput, mDialog);
                    }
                });
        mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                validationCodeSuccess = false;
            }
        });
        mDialog.setCancelable(false);

        Single.just(new RequestPictureVerification())
                .doOnSuccess(new Consumer<RequestPictureVerification>() {
                    @Override
                    public void accept(RequestPictureVerification requestPictureVerification) throws Exception {
                        requestPictureVerification.setPhone(phone);
                    }
                })
                .flatMap(new Function<RequestPictureVerification, SingleSource<OpenApiResult<PictureVerificationResultBean>>>() {
                    @Override
                    public SingleSource<OpenApiResult<PictureVerificationResultBean>> apply(RequestPictureVerification requestPictureVerification) throws Exception {
                        return verificationService.getPictureVerification(requestPictureVerification)
                                .compose(provider.bindUntilEvent(Lifecycle.Event.ON_DESTROY));
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new OpenApiResultObserver<PictureVerificationResultBean>() {
                    @Override
                    public void onLoading(Disposable d) {
                        onVerificationOptionByPictureSmsListener.onLoading();
                    }

                    @Override
                    public void onSuccess(OpenApiResult<PictureVerificationResultBean> result, PictureVerificationResultBean pictureVerificationResultBean) {
                        mDialog.show();
                        /**
                         * 设置图片验证码
                         */
                        Glide.with(context)
                                .load(result.getData().getPicture())
                                .into(binding.pictureCode);
                    }

                    @Override
                    public void onApiError(OpenApiResult<PictureVerificationResultBean> result, int code, String msg) {
                        ToastManager.show(context, msg);
                    }

                    @Override
                    public void onOtherError(Throwable e) {
                        ToastManager.show(context, e.getMessage());
                    }

                    @Override
                    public void onLoaded() {
                        onVerificationOptionByPictureSmsListener.onLoaded();
                    }
                });
    }

    /**
     *
     * @param phone
     * @param onVerificationOptionByPictureSmsListener
     */
    private void getPictureCode(Context context, String phone, LayoutVerificationBinding binding, final OnVerificationOptionByPictureSmsListener onVerificationOptionByPictureSmsListener) {
        /**
         * 1.获取图片验证码
         */
        Single.just(new RequestPictureVerification())
                .doOnSuccess(new Consumer<RequestPictureVerification>() {
                    @Override
                    public void accept(RequestPictureVerification requestPictureVerification) throws Exception {
                        requestPictureVerification.setPhone(phone);
                    }
                })
                .flatMap(new Function<RequestPictureVerification, SingleSource<OpenApiResult<PictureVerificationResultBean>>>() {
                    @Override
                    public SingleSource<OpenApiResult<PictureVerificationResultBean>> apply(RequestPictureVerification requestPictureVerification) throws Exception {
                        return verificationService.getPictureVerification(requestPictureVerification)
                                .compose(provider.bindUntilEvent(Lifecycle.Event.ON_DESTROY));
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new OpenApiResultObserver<PictureVerificationResultBean>() {
                    @Override
                    public void onLoading(Disposable d) {
                        onVerificationOptionByPictureSmsListener.onLoading();
                    }

                    @Override
                    public void onSuccess(OpenApiResult<PictureVerificationResultBean> result, PictureVerificationResultBean pictureVerificationResultBean) {
                        /**
                         * 设置图片验证码
                         */
                        Glide.with(context)
                                .load(result.getData().getPicture())
                                .into(binding.pictureCode);
                    }

                    @Override
                    public void onApiError(OpenApiResult<PictureVerificationResultBean> result, int code, String msg) {
                        ToastManager.show(App.getContext(), msg);
                    }

                    @Override
                    public void onOtherError(Throwable e) {
                        ToastManager.show(App.getContext(), e.getMessage());
                    }

                    @Override
                    public void onLoaded() {
                        onVerificationOptionByPictureSmsListener.onLoaded();
                    }
                });
    }

    /**

     * @param phone
     * @param dynamicCode
     * @param type
     * @param binding
     * @param onVerificationOptionByPictureSmsListener
     */
    private void getSmsCode(String phone, String dynamicCode, String type, LayoutVerificationBinding binding, final OnVerificationOptionByPictureSmsListener onVerificationOptionByPictureSmsListener) {
        if (timerDisposable != null && !timerDisposable.isDisposed()) {
            timerDisposable.isDisposed();
        }
        Single.just(new RequestSmsVerification())
                .doOnSuccess(new Consumer<RequestSmsVerification>() {
                    @Override
                    public void accept(RequestSmsVerification requestSmsVerification) throws Exception {
                        requestSmsVerification.setDynamicCode(dynamicCode);
                        requestSmsVerification.setPhone(phone);
                        requestSmsVerification.setType(type);
                    }
                })
                .flatMap(new Function<RequestSmsVerification, SingleSource<OpenApiResult<Object>>>() {
                    @Override
                    public SingleSource<OpenApiResult<Object>> apply(RequestSmsVerification requestSmsVerification) throws Exception {
                        return verificationService.getSmsVerification(requestSmsVerification)
                                .compose(provider.bindUntilEvent(Lifecycle.Event.ON_DESTROY));
                        }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new OpenApiResultObserver<Object>() {

                    @Override
                    public void onLoading(Disposable d) {
                        onVerificationOptionByPictureSmsListener.onLoading();
                    }

                    @Override
                    public void onSuccess(OpenApiResult<Object> result, Object o) {
                        /**
                         * 动态吗输入正确
                         */
                        validationCodeSuccess = true;
                        /**
                         * 发送成功,倒计时
                         */
                        onVerificationOptionByPictureSmsListener.onSendSmsCodeSuccess();
                        Observable.interval(1, TimeUnit.SECONDS)
                                .take(60)
                                .compose(provider.bindUntilEvent(Lifecycle.Event.ON_DESTROY))
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Observer<Long>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {
                                        timerDisposable = d;
                                        binding.getSmsCode.setEnabled(false);
                                    }

                                    @Override
                                    public void onNext(Long aLong) {
                                        binding.getSmsCode.setText((60 - aLong) + "s");
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        binding.getSmsCode.setEnabled(true);
                                        binding.getSmsCode.setText("获取验证码");
                                    }

                                    @Override
                                    public void onComplete() {
                                        binding.getSmsCode.setEnabled(true);
                                        binding.getSmsCode.setText("获取验证码");
                                    }
                                });
                    }

                    @Override
                    public void onApiError(OpenApiResult<Object> result, int code, String  msg) {
                        ToastManager.show(App.getContext(), msg);
                        /**
                        30000	操作失败
                        33055	您的手机号已经注册过，请登录
                        30048	请输入正确的手机号码
                        33068	您输入的动态码不正确，请检查
                        33069	您的动态码已过期，请重新获取
                        30037	手机未注册
                        30024	类型不能为空
                        35340	动态码不能为空
                         */
                        switch (code) {
                            case 30000 :
                                break;
                            case 33055 :
                                break;
                            case 30048 :
                                break;
                            case 33068 :
                                break;
                            case 33069 :
                                break;
                            case 30037 :
                                break;
                            case 30024 :
                                break;
                            case 35340 :
                                break;
                        }
                        validationCodeSuccess = false;
                    }

                    @Override
                    public void onOtherError(Throwable e) {
                        validationCodeSuccess = false;
                        ToastManager.show(App.getContext(), e.getMessage());
                    }

                    @Override
                    public void onLoaded() {
                        onVerificationOptionByPictureSmsListener.onLoaded();
                    }
                });
    }

    public static interface OnVerificationOptionByPictureSmsListener {

        void onLoading();

        void onLoaded();

        /**
         * 获取图片验证码成功
         * @param picture
         */
        void getPictureCodeSuccess(byte[] picture);

        /**
         * 发送短信成功
         */
        void onSendSmsCodeSuccess();

        /**
         * 确认兑换
         * @param smsCodeInput
         */
        void toExchange1(String smsCodeInput, MaterialDialog mDialog);
    }

    /**
     * 短信类型（
     * type=2为兑换礼品获取验证码
     * type=3为红包获取验证码
     * type=4为提现获取验证码）
     * @param context
     * @param type
     * @param phone 需要发送短信判断返回的phone
     * @param smsChannel 需要发送短信判断返回的smsChannel
     * @param onVerificationOptionByAutoSendListener
     */
    public void showVerificationByAutoSendMessage(Context context, int type, String phone, String smsChannel, final OnVerificationOptionByAutoSendListener onVerificationOptionByAutoSendListener) {
        this.type = type;
        this.phone = phone;
        this.smsChannel = smsChannel;
        MaterialDialog mDialog = new MaterialDialog.Builder(context)
                .content("点击发送短信确认商品兑换。\n短信验证码每天只能发送10次，如需继续操作,请联系客服。")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        getSmsCodeForExchange(dialog, context, type, phone, onVerificationOptionByAutoSendListener);
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                    }
                })
                .build();
        mDialog.setCancelable(false);
        mDialog.show();
    }

    /**
     * 通知服务器接受短信
     * @param context
     * @param type
     * @param phone
     * @param onVerificationOptionByAutoSendListener
     */
    private void getSmsCodeForExchange(MaterialDialog dialog, Context context, int type, String phone, final OnVerificationOptionByAutoSendListener onVerificationOptionByAutoSendListener) {
        Single.just(new RequestAutoSendMessage())
                .doOnSuccess(new Consumer<RequestAutoSendMessage>() {
                    @Override
                    public void accept(RequestAutoSendMessage requestAutoSendMessage) throws Exception {
                        requestAutoSendMessage.setPhone(phone);
                        requestAutoSendMessage.setType(type);
                    }
                })
                .flatMap(new Function<RequestAutoSendMessage, SingleSource<OpenApiResult<Object>>>() {
                    @Override
                    public SingleSource<OpenApiResult<Object>> apply(RequestAutoSendMessage requestAutoSendMessage) throws Exception {
                        return verificationService.getAutoSendMessage(requestAutoSendMessage)
                                .compose(provider.bindUntilEvent(Lifecycle.Event.ON_DESTROY));
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new OpenApiResultObserver<Object>() {
                    @Override
                    public void onLoading(Disposable d) {
                        onVerificationOptionByAutoSendListener.onLoading();
                    }

                    @Override
                    public void onSuccess(OpenApiResult<Object> result, Object o) {

                        showVerificationAutoSend(context, type, phone, onVerificationOptionByAutoSendListener);

                        /**
                         * 确认兑换,跳转到短信发送界面
                         */
                        Uri uri = Uri.parse("smsto:" + smsChannel);
                        Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
                        String message = "礼品兑换账号:" + phone + "," + (System.currentTimeMillis() / 1000);
                        Log.d("test", "message : " + message);
                        sendIntent.putExtra("sms_body", message);
                        context.startActivity(sendIntent);
                        dialog.dismiss();

                    }

                    @Override
                    public void onApiError(OpenApiResult<Object> result, int code, String msg) {
                        ToastManager.show(context, msg);
                        dialog.dismiss();
//                        showVerificationAutoSend(context, type, phone, onVerificationOptionByAutoSendListener);
                    }

                    @Override
                    public void onOtherError(Throwable e) {
                        ToastManager.show(context, e.getMessage());
                        dialog.dismiss();
//                        showVerificationAutoSend(context, type, phone, onVerificationOptionByAutoSendListener);
                    }

                    @Override
                    public void onLoaded() {
                        onVerificationOptionByAutoSendListener.onLoaded();
                    }
                });
    }

    /**
     * 通知服务器轮询用户发送的短信,接受后向用户发送短信,
     * 短信类型（
     * type=2为兑换礼品获取验证码
     * type=3为红包获取验证码
     * type=4为提现获取验证码)
     * @param context
     * @param type
     * @param phone
     * @param onVerificationOptionByAutoSendListener
     */
    private void showVerificationAutoSend(Context context, int type, String phone, final OnVerificationOptionByAutoSendListener onVerificationOptionByAutoSendListener) {
        MaterialDialog mDialog = new MaterialDialog.Builder(context)
                .customView(R.layout.layout_verification_2, true)
                .dismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (timerDisposable2 != null && !timerDisposable2.isDisposed()) {
                            timerDisposable2.dispose();
                        }
                    }
                })
                .build();
        View customView = mDialog.getCustomView();
        LayoutVerification2Binding binding = DataBindingUtil.bind(customView);
        binding.message.setText("兑换优惠券短信发送成功后\n验证码将发送至 " + smsChannel);
        RxView.clicks(binding.close)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (timerDisposable2 != null && !timerDisposable2.isDisposed()) {
                            timerDisposable2.dispose();
                        }
                        mDialog.dismiss();
                    }
                });
        /**
         * 重试发送兑换短信
         */
        RxView.clicks(binding.getSmsAgain)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Single.just(new RequestAutoSendMessage())
                                .doOnSuccess(new Consumer<RequestAutoSendMessage>() {
                                    @Override
                                    public void accept(RequestAutoSendMessage requestAutoSendMessage) throws Exception {
                                        requestAutoSendMessage.setPhone(phone);
                                        requestAutoSendMessage.setType(type);
                                    }
                                })
                                .flatMap(new Function<RequestAutoSendMessage, SingleSource<OpenApiResult<Object>>>() {
                                    @Override
                                    public SingleSource<OpenApiResult<Object>> apply(RequestAutoSendMessage requestAutoSendMessage) throws Exception {
                                        return verificationService.getAutoSendMessage(requestAutoSendMessage)
                                                .compose(provider.bindUntilEvent(Lifecycle.Event.ON_DESTROY));
                                    }
                                })
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new OpenApiResultObserver<Object>() {
                                    @Override
                                    public void onLoading(Disposable d) {
                                        onVerificationOptionByAutoSendListener.onLoading();
                                    }

                                    @Override
                                    public void onSuccess(OpenApiResult<Object> result, Object o) {

                                        /**
                                         * 重新生成短信编辑内容
                                         */
                                        Uri uri = Uri.parse("smsto:" + smsChannel);
                                        Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
                                        String message = "礼品兑换账号:" + phone + "," + (System.currentTimeMillis() / 1000);
                                        Log.d("test", "message : " + message);
                                        sendIntent.putExtra("sms_body", message);
                                        context.startActivity(sendIntent);

                                        Observable.interval(1, TimeUnit.SECONDS)
                                                .take(60)
                                                .compose(provider.bindUntilEvent(Lifecycle.Event.ON_DESTROY))
                                                .subscribeOn(Schedulers.io())
                                                .observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(new Observer<Long>() {

                                                    @Override
                                                    public void onSubscribe(Disposable d) {
                                                        timerDisposable2 = d;
                                                        binding.getSmsAgain.setEnabled(false);
                                                    }

                                                    @Override
                                                    public void onNext(Long aLong) {
                                                        binding.getSmsAgain.setText((60 - aLong) + "s");
                                                    }

                                                    @Override
                                                    public void onError(Throwable e) {
                                                        binding.getSmsAgain.setEnabled(true);
                                                        binding.getSmsAgain.setText("重新发送兑换短信");
                                                    }

                                                    @Override
                                                    public void onComplete() {
                                                        binding.getSmsAgain.setEnabled(true);
                                                        binding.getSmsAgain.setText("重新发送兑换短信");
                                                    }
                                                });
                                    }

                                    @Override
                                    public void onApiError(OpenApiResult<Object> result, int code, String msg) {
                                        ToastManager.show(context, msg);
                                    }

                                    @Override
                                    public void onOtherError(Throwable e) {
                                        ToastManager.show(context, e.getMessage());
                                    }

                                    @Override
                                    public void onLoaded() {
                                        onVerificationOptionByAutoSendListener.onLoaded();
                                    }
                                });
                    }
                });
        binding.verificationCodeView.setInputCompleteListener(new VerificationCodeView.InputCompleteListener() {

            @Override
            public void inputComplete() {
                String inputContent = binding.verificationCodeView.getInputContent();
                Logger.d("inputContent : " + inputContent);
                if (inputContent.length() >= 6) {
                    onVerificationOptionByAutoSendListener.toExchange2(inputContent, mDialog);
                }
            }

            @Override
            public void deleteContent() {

            }
        });
        mDialog.setCancelable(false);
        mDialog.show();
    }

    public static interface OnVerificationOptionByAutoSendListener {

        void onLoading();

        void onLoaded();

        /**
         * 确认兑换
         * @param smsCodeInput
         */
        void toExchange2(String smsCodeInput, MaterialDialog mDialog);
    }
}
